package com.lm.activiti;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.repository.ProcessDefinition;
import org.apache.commons.io.FileUtils;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lm_jcf
 * @date 2018/5/7 16:11
 */
public class ProcessDefinitionTest {

    ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();

    //查看流程定义图片
    @Test
    public void viewPic() throws IOException {
        //将生成图片放在文件夹下
        String deploymentId = "1201";

        List<String> list = processEngine.getRepositoryService().getDeploymentResourceNames(deploymentId);

        //定义图片资源名称
        String resourceName = "";

        if (list != null && list.size() > 0){
            for (String s : list) {
                if (s.indexOf(".png") >=0 ){
                    resourceName = s;
                }
            }
        }

        //获取图片的输入流
        InputStream in = processEngine.getRepositoryService()
                .getResourceAsStream(deploymentId, resourceName);
        //将图片生成到
        File file = new File("D:/" + resourceName);
        //将输入流写入
        FileUtils.copyInputStreamToFile(in,file);

    }

    //查询最新版本的流程定义
    //使用map的key不可重复特性，使用流程定义的key唯一作为map的key，每次put都覆盖value
    @Test
    public void findLastVersionProcessDefinition(){
        List<ProcessDefinition> list = processEngine.getRepositoryService()
                .createProcessDefinitionQuery()
                /** 查询条件（where部分）*/
                .orderByProcessDefinitionVersion().asc()   //使用流程定义的版本升序排序
                .list();

        Map<String,ProcessDefinition> map = new LinkedHashMap<String, ProcessDefinition>();
        if (list != null && list.size()>0 ){
            for (ProcessDefinition processDefinition : list) {
                map.put(processDefinition.getKey(),processDefinition);
            }
        }

        List<ProcessDefinition> pdLIst = new ArrayList<ProcessDefinition>(map.values());
        if (pdLIst != null && pdLIst.size() >0){
            for (ProcessDefinition processDefinition : pdLIst) {
                System.out.println("流程定义Id："+processDefinition.getId());
                System.out.println("流程定义名称："+processDefinition.getName());
                System.out.println("流程定义Key："+processDefinition.getKey());
                System.out.println("流程定义版本："+processDefinition.getVersion());
                System.out.println("流程定义bpmn文件："+processDefinition.getResourceName());
                System.out.println("流程定义png文件："+processDefinition.getDiagramResourceName());
                System.out.println("部署对象ID："+processDefinition.getDeploymentId());
            }
        }
    }
}
